package com.example.xutils1.fragment;

import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.example.xutils1.MainActivity.OnLayoutOpenListener;
import com.example.xutils1.R;
import com.example.xutils1.adapter.HeaderViewAdapter;
import com.example.xutils1.adapter.JiuJiuListAdapter;
import com.example.xutils1.bean.JiuJiuItem;
import com.example.xutils1.bean.JiuJiuJson;
import com.example.xutils1.bean.PagerItem;
import com.example.xutils1.bean.PagerItem.HeaderPagerJson;
import com.example.xutils1.constant.URL;
import com.example.xutils1.utils.RequestCallBackEx;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.viewpagerindicator.CirclePageIndicator;

public class JiuJiuFragment extends Fragment {

	private boolean isFirst = true;

	private OnLayoutOpenListener mListener;

	private SwipeRefreshLayout mRefreshLayout;
	private ListView mListView;

	private JiuJiuListAdapter mAdapter;
	private HeaderViewAdapter mHeaderViewAdapter;

	private HttpUtils mHttpUtils;
	private DbUtils mDbUtils;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHttpUtils = new HttpUtils();
		mDbUtils = DbUtils.create(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fgm_jiujiu, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		View view = getView();

		// 璁剧疆鍒濆鍖栦笅鎷夊埛鏂�
		mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
		mRefreshLayout.setColorScheme(R.color.color1, R.color.color2, R.color.color3, R.color.color4);
		// 璁剧疆涓嬫媺鍒锋柊鐨勭洃鍚櫒
		mRefreshLayout.setOnRefreshListener(mRefreshListener);

		// 褰揊ragment澶嶇敤鐨勬椂鍊欙紝鑻ュ彂鐜癆dapter宸茬粡瀛樺湪锛屽垯浣跨敤涔嬪墠鐨凙dapter灏卞彲浠ヤ簡
		if (mAdapter == null) {
			mAdapter = new JiuJiuListAdapter(getActivity());
		}

		mListView = (ListView) view.findViewById(R.id.lv);
		mListView.addHeaderView(initHeaderView(), null, false);
		mListView.setAdapter(mAdapter);

		view.findViewById(R.id.header_left_btn).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mListener != null) {
					mListener.openLayout();
				}
			}
		});

		// 褰撶涓�鍚姩搴旂敤绋嬪簭鐨勬椂鍊欙紝鍏堜粠鏈湴宸茬粡缂撳瓨鐨勬暟鎹簱涓彇鏁版嵁
		// 杩欐牱鍦ㄨ繘鍏ュ簲鐢ㄧ▼搴忕殑鏃跺�灏变細椹笂鏄剧ず鍑轰箣鍓嶇紦瀛樺ソ鐨勬暟鎹�
		if (isFirst) {
			try {
				List<JiuJiuItem> list = mDbUtils.findAll(JiuJiuItem.class);
				if (list != null) {
					mAdapter.setData(list);
					mAdapter.notifyDataSetChanged();
				}
			} catch (DbException e) {
				e.printStackTrace();
			}

			try {
				List<PagerItem> list = mDbUtils.findAll(PagerItem.class);
				if (list != null) {
					mHeaderViewAdapter.setData(list);
					mHeaderViewAdapter.notifyDataSetChanged();
				}
			} catch (Exception e) {
			}

			// 褰揊ragment澶嶇敤鐨勬椂鍊欙紝鍙戠幇鏁版嵁涓嶄负绌猴紝鍒欎笉闇�閲嶆柊璇锋眰鏁版嵁
			requestData();
			requestHeaderData();
			mRefreshLayout.setRefreshing(true);

			isFirst = false;
		}
	}

	/**
	 * 鍒濆鍖朙istView鐨凥eaderView
	 */
	private View initHeaderView() {

		View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.list_header, null);

		if (mHeaderViewAdapter == null) {
			mHeaderViewAdapter = new HeaderViewAdapter(getActivity());
		}

		ViewPager pager = (ViewPager) headerView.findViewById(R.id.pager);
		// 寰�istView鐨勫ご閮ㄨ缃甐iewPager鐨勬椂鍊欙紝涓�畾瑕佹墜鍔ㄧ粰浠栬缃ソsetLayoutParams锛屽苟涓旈珮搴﹁璁剧疆涓�釜鍥哄畾鐨勫�
		// 涓嶈兘鏄疻RAP_CONTENT鎴栬�MATCH_PARENT
		// pager.setLayoutParams(new
		// AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, dp2px(210)));
		pager.setAdapter(mHeaderViewAdapter);

		CirclePageIndicator indicator = (CirclePageIndicator) headerView.findViewById(R.id.indicator);
		indicator.setViewPager(pager);

		indicator.setFillColor(Color.GRAY);
		indicator.setPageColor(Color.WHITE);
		indicator.setRadius(dp2px(5));
		indicator.setCentered(true);

		return headerView;
	}

	private int dp2px(int dp) {
		return (int) (dp * getActivity().getResources().getDisplayMetrics().density);
	}

	/**
	 * 鑾峰彇澶撮儴鐨勬暟鎹�
	 */
	private void requestHeaderData() {
		mHttpUtils.send(HttpMethod.GET, URL.VIEWPAGE_HEADER, new RequestCallBackEx<HeaderPagerJson>(HeaderPagerJson.class) {

			@Override
			public void onSuccess(final HeaderPagerJson obj) {
				mHeaderViewAdapter.setData(obj.data);
				mHeaderViewAdapter.notifyDataSetChanged();

				// 鏁版嵁搴撴搷浣滄�鑳借緝浣庯紝灏介噺鍦ㄧ嚎绋嬩腑缁忚锛屼互鍏嶉樆濉炰富绾跨▼
				new Thread() {
					@Override
					public void run() {
						try {
							mDbUtils.deleteAll(PagerItem.class);
							mDbUtils.saveOrUpdateAll(obj.data);
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				}.start();
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}
		});
	}

	/**
	 * 鑾峰彇鍒楄〃鐨勬暟鎹�
	 */
	private void requestData() {
		mHttpUtils.send(HttpMethod.GET, URL.LIST_JIUJIU, mCallBack);
	}

	/**
	 * ListView鍒楄〃鐨勬暟鎹姹傛垚鍔熶箣鍚庣殑鍥炶皟
	 */
	private RequestCallBackEx<JiuJiuJson> mCallBack = new RequestCallBackEx<JiuJiuJson>(JiuJiuJson.class) {

		@Override
		public void onSuccess(final JiuJiuJson obj) {
			mAdapter.setData(obj.list);
			mAdapter.notifyDataSetChanged();

			// 璁╀笅鎷夊埛鏂扮殑甯冨眬鍋滄鍒锋柊
			mRefreshLayout.setRefreshing(false);

			new Thread() {
				@Override
				public void run() {
					try {
						// 瀵硅姹傚埌鐨勬暟鎹繘琛岀紦瀛�
						// 杩欐牱鍦ㄤ笅娆¤繘绋嬪簭锛屾垨鑰呮病鏈夌綉鐨勬儏鍐典笅锛屽氨鍙互鍏堜娇鐢ㄧ紦瀛樼殑鏁版嵁
						mDbUtils.deleteAll(JiuJiuItem.class);
						mDbUtils.saveOrUpdateAll(obj.list);
					} catch (DbException e) {
						e.printStackTrace();
					}
				}
			}.start();
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(getActivity(), "璇锋眰澶辫触锛岃閲嶆柊灏濊瘯", Toast.LENGTH_LONG).show();
			mRefreshLayout.setRefreshing(false);
		}
	};

	private OnRefreshListener mRefreshListener = new OnRefreshListener() {

		@Override
		public void onRefresh() {
			requestData();
			requestHeaderData();
		}
	};

	public void setOnLayoutOpenListener(OnLayoutOpenListener l) {
		mListener = l;
	}
}